package com.sakura.takeaway.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sakura.takeaway.common.R;
import com.sakura.takeaway.dto.SetmealDto;
import com.sakura.takeaway.entity.Category;
import com.sakura.takeaway.entity.Setmeal;
import com.sakura.takeaway.service.CategoryService;
import com.sakura.takeaway.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Sakura
 * @Date 2022-07-10 15:42
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("套餐信息：{}",setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 套餐管理分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true ),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true ),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false )
    })
    public R<Page> page(int page,int pageSize,String name){

        //构造分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper =new LambdaQueryWrapper<>();
        //根据name进行模糊查询
        queryWrapper.like(name!=null,Setmeal::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);

        //处理套餐分类显示name

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        //设置属性的值，records
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);

            //获取套餐分类id
            Long categoryId = item.getCategoryId();
            //根据套餐分类id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;

        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);

        return R.success(setmealDtoPage);
    }

    /**
     * 套餐删除功能
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "套餐删除接口")
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);

        setmealService.removeWithDish(ids);

        return R.success("套餐数据删除成功");
    }

    /**
     * 根据条件查询套餐分类对应的菜品信息
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    @ApiOperation(value = "套餐条件查询接口")
    public R<List<Setmeal>> list(Setmeal setmeal){

        //构造查询条件
        LambdaQueryWrapper<Setmeal> queryWrapper =new LambdaQueryWrapper();
        queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        //查询套餐（起售状态）为 1 的起售套餐
        queryWrapper.eq(Setmeal::getStatus,1);
        //条件排序条件
        queryWrapper.orderByAsc(Setmeal::getPrice).orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);
    }

    //---------------------------------完善功能-------------------------------------

    /**
     * 修改套餐状态
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping("/status/{status}")
    @ApiOperation(value = "套餐状态修改接口")
    public R<String> status(@PathVariable("status") Integer status,@RequestParam List<Long> ids){
        log.info("禁用菜品信息：{}",ids);

        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        //通过id查询套餐
        queryWrapper.in(Setmeal::getId,ids);

        List<Setmeal> list = setmealService.list(queryWrapper);

        list.stream().map((item)->{
            //设置套餐状态
            item.setStatus(status);
            setmealService.updateById(item);

            return item;
        }).collect(Collectors.toList());

        return R.success("销售状态修改成功");
    }

    /**
     * 根据id查询套餐信息 --> 用于套餐修改回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询套餐接口")
    public R<SetmealDto> getById(@PathVariable Long id){
        log.info("根据id查询套餐信息....");

        SetmealDto setmealDto = setmealService.getByIdWithDish(id);

        if(setmealDto!=null){
            return R.success(setmealDto);
        }

        return R.error("没有查询到对应的套餐");
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    @ApiOperation(value = "套餐修改接口")
    public R<String> update(@RequestBody SetmealDto setmealDto){

        log.info(setmealDto.toString());

        setmealService.updateWithDish(setmealDto);

        //清理某个分类下的缓存数据
        String key = setmealDto.getCategoryId()+"_"+setmealDto.getStatus();
        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }

}
